package com.qunar.qcf.handler;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qunar.qcf.core.service.IoHandlerAdapter;
import com.qunar.qcf.core.session.IdleStatus;
import com.qunar.qcf.core.session.IoSession;
import com.qunar.qcf.handler.transport.QCFInit;
import com.qunar.qcf.handler.transport.Transport;

/**
 * 抽象父类
 * 
 * @author zhangwan
 * @email wan.zhang@qunar.com
 */
public abstract class AbstractServerHandler extends IoHandlerAdapter {
	private final Logger logger = LoggerFactory.getLogger(AbstractServerHandler.class);
	protected final Map<String, InvokeHandler> handlers = new HashMap<String, InvokeHandler>();
	protected final Map<String, Method> initMethods = new HashMap<String, Method>();

	public AbstractServerHandler() {
		QCFInit.register(handlers, initMethods);
	}

	protected abstract void processor(IoSession session, Object message);

	@Override
	public void sessionOpened(IoSession session) throws Exception {
	}

	@Override
	public void sessionClosed(IoSession session) {
	}

	@Override
	@Deprecated
	public final void exceptionCaught(IoSession session, Throwable cause) throws Exception {
	}

	@Override
	@Deprecated
	public final void messageReceived(IoSession session, Object message) throws Exception {
		Transport t = (Transport) message;
		String className = t.getClazz();
		String methodName = t.getMethod();
		logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ":调用的Handler名称为:" + className + ";调用方法为:" + methodName);
		processor(session, message);
	}

	@Override
	@Deprecated
	public final void messageSent(IoSession session, Object message) throws Exception {
	}

	@Override
	@Deprecated
	public final void sessionIdle(IoSession session, IdleStatus status) throws Exception {
	}

	@Override
	@Deprecated
	public final void sessionCreated(IoSession session) throws Exception {
	}

}
